<?php

/**
 * 类名：Driver
 * 作者：mqycn
 * 博客：http://www.miaoqiyuan.cn
 * 源码：https://gitee.com/mqycn/ShortUrl
 * 说明：抽象存储类
 */

namespace drivers\core;

require_once __DIR__ . '/IntConvert.php';

abstract class Driver {

	/**
	 * 创建URL
	 */
	public function create($url) {
		$result = $this->query('url', ['url' => $url]);
		if (empty($result)) {
			$index = $this->getMaxId();
			$index++;
			$key = \IntConvert::toString($index);
			$this->insert('url', [
				'key' => $key,
				'url' => $url,
			]);
			$this->setMaxId($index);
			return $key;
		} else {
			return $result[0]['key'];
		}
	}

	/**
	 * 返回URL
	 */
	public function get($key) {
		$result = $this->query('url', ['key' => $key]);
		if (empty($result)) {
			return '';
		} else {
			return $result[0]['url'];
		}
	}

	/**
	 * 安装
	 */
	public function install() {
		if (empty($this->query('config', ['key' => 'max_id']))) {
			$this->insert('url', ['key' => 'index', 'url' => 'http://www.baidu.com']);
			$this->insert('config', ['key' => 'max_id', 'value' => 1]);
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取最大值
	 */
	protected function getMaxId() {
		$result = $this->query('config', ['key' => 'max_id']);
		if (empty($result)) {
			return 1;
		} else {
			return (int) $result[0]['value'];
		}
	}

	/**
	 * 获取最大值
	 */
	protected function setMaxId($max_id) {
		$this->update('config', ['key' => 'max_id'], ['value' => $max_id]);
	}

	//插入记录
	abstract protected function insert($table, $data, $features = []);

	//查询记录
	abstract protected function query($table, $where = [], $sort = [], $features = []);

	//更新记录
	abstract protected function update($table, $where, $data, $features = []);

}